package com.dengxiujun.simpletomcat.handler;

import com.dengxiujun.simpletomcat.dispatcher.ServletDispatcher;
import com.dengxiujun.simpletomcat.request.HttpRequest;
import com.dengxiujun.simpletomcat.response.HttpResponse;

import java.io.IOException;
import java.net.Socket;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class ConnectionHandler implements Runnable {

    private Socket socket;

    public ConnectionHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            HttpRequest req = new HttpRequest(socket.getInputStream());
            HttpResponse rep = new HttpResponse(socket.getOutputStream());
            try {
                ServletDispatcher.dispatch(req, rep);
            } catch (RuntimeException e) {
                rep.write(e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}
